const deviceService = require('../service/deviceService')
const code = require('../common/code')
const auth = require('../middleware/auth')
const KoaRouter = require('koa-router')
const ExcelJS = require('exceljs')
const qs = require('qs')
const path = require('path')
const router = new KoaRouter()

// 查询闲置磅秤
router.get('/deviceListFree', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.getAllFree(ctx.session.user.store_id))
})

// 查询分店所有设备信息
router.get('/deviceList', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.getAll(ctx.session.user.store_id, qs.parse(ctx.query)))
})

// 查询某一个设备的信息
router.get('/device/:id', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.getOne(ctx.params.id, ctx.session.user.store_id))
})

// 查询分店某一个设备的维修记录
router.get('/deviceRepair/:id', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.getAllRepair(ctx.params.id, ctx.session.user.store_id))
})

// 分店增加一个设备
router.post('/device', auth(['EDP']), async ctx => {
    const device = ctx.request.body
    device.store_id = ctx.session.user.store_id
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.insert(device))
})

// 分店更新一个设备信息
router.put('/device/:id', auth(['EDP']), async ctx => {
    await deviceService.update(ctx.params.id, ctx.session.user.store_id, ctx.request.body)
    ctx.body = code.getCode(code.SUCCESS)
})

// 分店删除一个设备
router.delete('/device/:id', auth(['EDP']), async ctx => {
    await deviceService.del(ctx.params.id, ctx.session.user.store_id)
    ctx.body = code.getCode(code.SUCCESS)
})

// 分店导出设备信息到EXCEL
router.get('/deviceExport', auth(['EDP']), async ctx => {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('device')
    worksheet.views = [{ state: 'frozen', topLeftCell: 'B1' }]
    worksheet.columns = [
        { header: '设备序号', key: 'id' },
        { header: '店别', key: 'store' },
        { header: '设备名称', key: 'name' },
        { header: '设备型号', key: 'model' },
        { header: '设备序列号', key: 'serial' },
        { header: '设备标识', key: 'identify' },
        { header: 'IP地址', key: 'ip', width: 32 },
        { header: 'MAC物理地址', key: 'mac' },
        { header: '使用部门/位置', key: 'department' },
        { header: '保修起始日期', key: 'begin' },
        { header: '保修终止日期', key: 'end' },
        { header: '备注', key: 'remark' },
    ]
    worksheet.addRow({
        id: 'PC001',
        store: '海城店',
        name: '电脑主机',
        model: 'M4305s',
        serial: '000621',
        identify: 'ed01',
        ip: '172.18.23.10',
        mac: 'MAC物理地址',
        department: '技术课',
        begin: '2020-01-10',
        end: '2023-01-10',
        remark: '备注',
    })
    const deviceList = await deviceService.getAllByStoreId(ctx.session.user.store_id)
    deviceList.forEach(element => {
        worksheet.addRow({
            id: 'PC001',
            store: ctx.session.user.storeName,
            name: element.name,
            model: element.model,
            serial: element.serial,
            identify: element.identify,
            ip: element.ip,
            mac: element.mac,
            department: element.Department.name,
            begin: element.begin,
            end: element.end,
            remark: element.remark,
        })
    })
    ctx.body = code.getCode(code.SUCCESS, null, await workbook.xlsx.writeBuffer())
})

// 分店导出设备信息到EXCEL 4日作业
/* 太复杂了
router.get('/deviceExport4Work', auth(['EDP']), async ctx => {
    const workbook = new ExcelJS.Workbook()
    await workbook.xlsx.readFile(path.resolve(__dirname, '../excel/4.xlsx'))
    // 按 name 提取工作表
    const worksheet = workbook.getWorksheet('PC机')
    let deviceList = await deviceService.getAllByStoreId(ctx.session.user.store_id)
    deviceList = deviceList.map(item => item.toJSON())
    console.log(deviceList)
    const pcDeviceList = deviceList.filter(item => item.Category.type === 'DN-6')
    console.log(pcDeviceList)
    pcDeviceList.forEach(element => {
        worksheet.addRow([element.identify, element.ip, element.Department.name, element.model])
    })
    const lastIndex = pcDeviceList.length
    setBorderStyle('A', 4, 'C', 3 + lastIndex)
    ctx.body = code.getCode(code.SUCCESS, null, await workbook.xlsx.writeBuffer())

    function setBorderStyle(top, l, bottom, r) {
        let t = top.charCodeAt(),
            b = bottom.charCodeAt()
        for (let i = t; i <= b; i++) {
            for (let j = l; j <= r; j++) {
                let borderStyle = {
                    top: { style: j === l ? 'medium' : 'thin' },
                    left: { style: i === t ? 'medium' : 'thin' },
                    bottom: { style: j === r ? 'medium' : 'thin' },
                    right: { style: i === b ? 'medium' : 'thin' },
                }
                worksheet.getCell(String.fromCharCode(i) + j).border = borderStyle
            }
        }
    }
})
*/

// 按分类查询设备数量
router.get('/getCountByCategory', auth(['EDP']), async ctx => {
    ctx.body = code.getCode(code.SUCCESS, null, await deviceService.getCountByCategory())
})

module.exports = router
